package com.king.security.exception.handle;

import com.king.security.base.Result;
import com.king.security.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @description:
 * @author: HHJ
 * @create: 2019-09-27 13:55
 **/
@Slf4j
@RestControllerAdvice
public class ExceptionHandle {

    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public Result hanlerException(Exception e) {
        log.error("系统异常", e);
        return Result.buildError();
    }

    @ResponseBody
    @ExceptionHandler(value = RuntimeException.class)
    public Result hanlerException(RuntimeException e) {
        log.error("运行时异常", e);
        return Result.buildError();
    }

    @ResponseBody
    @ExceptionHandler(value = BusinessException.class)
    public Result hanlerException(BusinessException e) {
        log.error("业务处理发生了异常", e);
        return Result.buildError(e.getMsg());
    }

    @ResponseBody
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Result hanlerException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        StringBuilder sb = new StringBuilder();
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            sb.append(fieldError.getDefaultMessage() + "、");
        }
        log.warn("请求参数异常：{}", sb.toString());
        return Result.buildError(sb.toString());
    }

    @ResponseBody
    @ExceptionHandler(value = HttpMessageNotReadableException.class)
    public Result hanlerException(HttpMessageNotReadableException e) {
        log.error("请求参数无法解析", e);
        return Result.buildError();
    }

}
